package region

import (
	"context"
	"fast-boot/app/model"
	"github.com/hwUltra/fb-tools/gormx"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OptionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 菜单下拉列表
func NewOptionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OptionsLogic {
	return &OptionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OptionsLogic) Options() (resp []*types.SysRegionOption, err error) {
	//var items []*model.SysRegionModel
	//l.svcCtx.GormClient.GormDb.Model(model.SysRegionModel{}).
	//	Order("id asc ").
	//	Scan(&items)
	items := (*model.SysRegionCache)(gormx.NewCacheTool(l.svcCtx.Config.Cache, l.svcCtx.GormClient.GormDb)).List()
	return GetTree(items, 0), nil
}

func GetTree(list []*model.SysRegionModel, parentCode int64) []*types.SysRegionOption {
	res := make([]*types.SysRegionOption, 0)
	for _, item := range list {
		if item.ParentCode == parentCode {
			var r types.SysRegionOption
			r.Label = item.RegionName
			r.Value = item.RegionCode
			r.Children = GetTree(list, item.RegionCode)
			res = append(res, &r)
		}
	}
	return res
}
